package com.akcome.apollo.service.impl;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.akcome.apollo.common.ApolloConstants;
import com.akcome.apollo.common.SecurityUser;
import com.akcome.apollo.domain.BmpUser;
import com.akcome.apollo.domain.enums.YesOrNoEnum;
import com.akcome.apollo.repository.BmpUserRepository;


/**
 * @version V1.0.0
 * @Description Spring Security 用于将 数据库中的用户信息转换成 userDetail 对象的服务类的实现类
 * @Author liuyuequn weanyq@gmail.com
 * @Date 2017/8/2 16:43
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private BmpUserRepository bmpUserRepository;

    /**
     * 获取 userDetail
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public SecurityUser loadUserByUsername(String username) throws UsernameNotFoundException {

    	BmpUser user = bmpUserRepository.findByEmail(username);
    	
    	//TODO 查询角色，多个,隔开
    	String roles = ApolloConstants.ROLE_USER;

        if (user == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        } else {
        	Collection<? extends GrantedAuthority> authorities;
            try {
                authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(roles);
            } catch (Exception e) {
                authorities = null;
            }

            return new SecurityUser(
                    user.getId(),
                    user.getEmail(),
                    user.getPassword(),
                    user.getMobile(),
                    user.getLastPasswordReset(),
                    authorities,
                    user.getEnabled().equals(YesOrNoEnum.YES.getCode())
            );
        }
    }
}
